﻿@using NetSurveillance.WebApp.DataServices.Models
@model NetSurveillance.WebApp.Models.DataIMRecordListModel

@{
    ViewBag.Title = "即时聊天数据";
    Layout = "~/Views/Shared/_SimpleLayout.cshtml";
    ViewBag.DataIMRecordId = Model != null ? Model.DataIMRecordId : null;
}
@section javascript
{
    <script type="text/javascript">
        $(function() {
            $('#middle_right_begin').click(startOrPauseTask);
            $('#middle_right_end').click(stopTask);
            $('#middle_right_f5').click(autoSearch);
            $('#middle_right_prepage').click(function() {
                var pageIndex = parseInt($('#hidPageIndex').val());
                return goPage(pageIndex - 1);
            });
            $('#middle_right_nextpage').click(function() {
                var pageIndex = parseInt($('#hidPageIndex').val());
                return goPage(pageIndex + 1);
            });
            $('#middle_right_goto').click(goPage);
            $('#chk_checkall').change(checkAll);
            $('#middle_right_showall').click(displayAll);
            $('#middle_right_delete').click(deleteRecords);
            $('#middle_right_select').click(function() {
                var searchId = $('#SearchId').val();
                $.openModalDialog({
                    url: '@Url.Action("IMSearch", "Search")' + '?imSearchId=' + searchId,
                    width: '950px',
                    height: '610px',
                    scroll: false
                });
            });
            $('#middle_right_export').click(exportConfirm);
            $('#middle_right_downloadList').click(showIMFiles);
            @if (Model != null && Model.IsAutoSearch)
            {
                @("searchStart();")
            }
        });

        var autoSearchInterval;

        function autoSearch() {
            var $txtSec = $('#txt_second'),
                $hidIsAutoSearch = $('#IsAutoSearch'),
                $btnSearch = $('#middle_right_f5');
            if (!/^[0-9]*$/.test($txtSec.val())) {
                alert('间隔时间请输入数字');
                return false;
            }
            var intervalSec = $txtSec.val() == '' ? 0 : parseInt($txtSec.val());
            if (intervalSec <= 0) {
                searchOne();
                return false;
            }
            if ($hidIsAutoSearch.val() == '' || $hidIsAutoSearch.val().toLowerCase() == 'false') {
                autoSearchInterval = setInterval(searchOne, intervalSec * 1000);
                $btnSearch.find('a').text('停止刷新');
                $hidIsAutoSearch.val(true);
                $txtSec.attr('disabled', 'disabled');
                return false;
            }
            $btnSearch.find('a').text('刷新');
            $hidIsAutoSearch.val(false);
            clearInterval(autoSearchInterval);
            $txtSec.removeAttr('disabled');
            return false;
        }

        function searchOne() {
            var $hidMaxId = $('#hidMaxRecordId'),
                maxRecordId = parseFloat($hidMaxId.val()),
                localNum = $('#LocalNumber').val(),
                remoteNum = $('#RemoteNumber').val(),
                groupNum = $('#GroupNumber').val();
            $.showLoading('正在刷新数据，请等待');
            $.ajax({
                url: '@Url.Action("AutoSearch", "Task")',
                type: 'post',
                data: { maxRecordId: maxRecordId, type: 'dataIMRecord', localNum: localNum, remoteNum: remoteNum, groupNum: groupNum },
                dataType: 'html',
                success: function(html) {
                    $.hideLoading();
                    if (!html) return;
                    var $html = $(html);
                    $('#tbRecords tbody').prepend($html);
                    var currentMaxIdVal = $html.find('input[id^=hidMaxId]:first').val();
                    $hidMaxId.val(parseFloat(currentMaxIdVal) || $hidMaxId.val());
                    var $lblTotalCount = $('#lblTotalCount'),
                        totalCount = parseInt($lblTotalCount.text().trim()),
                        insertCount = $html.not('.trMaxId').size();
                    $lblTotalCount.text(totalCount + insertCount);
                }
            });
        }

        function goPage(goPageIndex) {
            if (typeof goPageIndex != 'number' && $('#txt_page').val() == '') {
                alert('请输入需要跳转的页数');
                return false;
            }
            $.showLoading('正在加载数据');
            if (typeof goPageIndex == 'number')
                $('#txt_page').val(goPageIndex);
            document.forms[0].submit();
            return false;
        }

        function checkAll() {
            var isCheckAll = $('#chk_checkall').is(':checked');
            $('#tbRecords tbody td:first-child :checkbox').attr('checked', isCheckAll);
        }

        function displayAll() {
            var $hidDisplayAll = $('#DisplayAll');
            $hidDisplayAll.val($hidDisplayAll.val() == 'False' || $hidDisplayAll.val() == 'false');
            return goPage();
        }

        function deleteRecords() {
            var $checkedEle = $('#tbRecords tbody :checkbox:checked');
            if ($checkedEle.size() == 0) {
                alert('请勾选要删除的记录');
                return false;
            }
            if (!window.confirm('@Resources.MessageResource.Delete_Confirm')) return false;
            var checkedIds = $.map($checkedEle, function(ele) {
                return parseFloat($(ele).val()) || -1;
            });
            $.ajax({
                url: '@Url.Action("DeleteRecords", "Task")',
                type: 'post',
                dataType: 'json',
                traditional: true,
                data: { dataRecordIds: checkedIds },
                success: function(result) {
                    if (result.success) {
                        $checkedEle.attr('checked', false);
                        window.location.replace(window.location.href);
                        return;
                    }
                    alert(result.message);
                }
            });
            return false;
        }

        function sortOrder(orderField, order) {
            var $hidOrderField = $('#OrderField'),
                $hidOrder = $('#Order');
            $hidOrderField.val(orderField);
            $hidOrder.val(order);
            return goPage();
        }

        function startOrPauseTask() {
            var $hidTaskStatus = $('#hidTaskStatus'),
                currTaskStatus = $hidTaskStatus.val();
            var setTaskStatus = '', loadingStr = '';
            if (currTaskStatus == $.enums.taskStatus.running) {
                setTaskStatus = $.enums.taskStatus.suspend;
                loadingStr = '正在暂停当前会话，请等待';
            } else if (currTaskStatus == $.enums.taskStatus.suspend) {
                setTaskStatus = $.enums.taskStatus.running;
                loadingStr = '正在开始当前会话，请等待';
            }
            $.ajax({
                url: '@Url.Action("SetTaskStatus", "Task")',
                type: 'post',
                dataType: 'json',
                data: { taskStatus: setTaskStatus },
                success: function(result) {
                    if (result && result.success) {
                        checkSetTaskStatus(function() {
                            $('#middle_right_begin a').text(setTaskStatus == $.enums.taskStatus.running ? '暂停' : '开始');
                            $hidTaskStatus.val(setTaskStatus);
                        });
                        $.showLoading(loadingStr);
                        return;
                    }
                    if (result && result.message)
                        alert(result.message);
                }
            });
            return false;
        }

        function stopTask() {
            if (!window.confirm('你确定要停止当前会话么？停止后当前会话即正常结束')) return false;
            $.ajax({
                url: '@Url.Action("SetTaskStatus", "Task")',
                type: 'post',
                dataType: 'json',
                data: { taskStatus: $.enums.taskStatus.stop },
                success: function(result) {
                    if (result && result.success) {
                        checkSetTaskStatus(function() {
                            $('#middle_right_begin,#middle_right_end').css('visibility', 'hidden');
                        });
                        $.showLoading('正在停止当前会话,请等待');
                        return;
                    }
                    if (result && result.message)
                        alert(result.message);
                }
            });
            return false;
        }

        function checkSetTaskStatus(succCallback) {
            $.ajax({
                url: '@Url.Action("CheckInteractive", "Task")',
                type: 'post',
                dataType: 'json',
                success: function(result) {
                    if (result && result.success) {
                        if (result.expandos && result.expandos.interactiveStatus != $.enums.interactive.starting) {
                            $.hideLoading();
                            if (result.expandos.interactiveStatus == $.enums.interactive.end &&
                                succCallback && typeof succCallback == 'function')
                                succCallback.call();
                        } else {
                            setTimeout(function() {
                                checkSetTaskStatus(succCallback);
                            }, 5000);
                        }
                        return;
                    }
                    if (result && result.message) {
                        alert(result.message);
                        $.hideLoading();
                    }
                }
            });
        }

        function exportConfirm() {
            var $checkedEle = $('#tbRecords tbody :checkbox:checked');
            if ($checkedEle.size() == 0) {
                alert('请勾选要导出的记录');
                return false;
            }
            var checkedIds = $.map($checkedEle, function(ele) {
                return parseFloat($(ele).val()) || -1;
            });
            $('#exportConfirmContain').dialog({
                title: '导出确认',
                width: 300,
                height: 150,
                closeOnEscape: false,
                draggable: false,
                resizable: false,
                modal: true,
                autoOpen: true,
                open: function() {
                    $(this).parent('.ui-dialog').find('.ui-dialog-titlebar-close').hide();
                },
                buttons: {
                    ' 是 ': function() {
                        exportRecords(checkedIds, true);
                    },
                    ' 否 ': function() {
                        exportRecords(checkedIds, false);
                    },
                    ' 取消 ': function() {
                        $(this).dialog('close');
                    }
                }
            });
            return false;
        }

        function exportRecords(ids, includeFile) {
            window.location.href =
                '@Url.Action("ExportRecords", "Task")?' + $.param({ drIds: ids, isIncludeFile: includeFile }, true);
            $('#exportConfirmContain').dialog('close');
        }
        @{
            string localNumber = Model == null ? string.Empty : Model.LocalNumber;
            string groupNumber = (Model == null || !string.IsNullOrWhiteSpace(Model.LocalNumber)) ?
                                     string.Empty : Model.GroupNumber;
        }
        function showIMFiles() {

            $('#imFilesContain').load('@Url.Action("IMFiles","Task")',
                { localNum: '@localNumber', groupNum:'@groupNumber'},
                function() {
                    $('#imFilesContain').dialog({
                        title: '文件列表',
                        width: 450,
                        height: 450,
                        modal: true,
                        autoOpen: true,
                        closeOnEscape: true
                    });
                });
        }
    </script>
}
@section css
{
    <style type="text/css">
        #tbRecords tbody tr td
        {
            min-width: 80px;
            border: .5px solid gray;
        }
        #tbRecords tbody tr td:first-child {
            min-width: inherit;
            width: 40px;
        }
        #tbRecords tbody tr td:nth-child(2),
        #tbRecords tbody tr td:nth-child(3),
        #tbRecords tbody tr td:nth-child(4) {
            width: 120px;
        }
        #tbRecords .currentDIMR td {
            color: red;
        }
    </style>
}
@using (Html.BeginForm())
{
    <div class="middle_right_title" id="middle_right_top">
        <div id="middle_right_begin" style="visibility: hidden;">
            <a href="javascript:;">
                @if (Model != null && Model.TaskStatus == TaskStatusType.Suspend)
                {
                    @("开始")
                }
                else if (Model != null && Model.TaskStatus == TaskStatusType.Running)
                {
                    @("暂停")
                }
            </a>
        </div>
        <div id="middle_right_end" style="visibility: hidden;">
            <a href="javascript:;">结束</a>
        </div>
        <div id="middle_right_f5">
            <a href="javascript:;">@(Model != null && Model.IsAutoSearch ? "停止" : "刷新")</a>
        </div>
        <div class="middle_right_font">
            间 隔 
            @Html.TextBoxFor(m => m.AutoSearchInterval, new { id = "txt_second" })
            秒
        </div>
        <div id="middle_right_select"><a href="javascript:;">查询</a></div>
        <div id="middle_right_delete" style="visibility: @((ViewBag.IsHideDelete??true) ? "hidden" : "")"><a href="javascript:;">删除</a></div>
        <div id="middle_right_export"><a href="javascript:;">导出</a></div>
        <div id="middle_right_downloadList"><a href="javascript:;">文件列表</a></div>
    </div>
    <div id="middle_right_body">
        @Html.ValidationSummary()
        <table id="tbRecords" class="middle_list_tab">
            <thead>
                <tr>
                    <th></th>
                    <th>时间</th>
                    <th>发送方</th>
                    <th>接收方</th>
                    <th>内容</th>
                </tr>
            </thead>
            <tbody>
                @Html.Partial("../Task/_DataIMRecords", Model == null ? null : Model.DataIMRecords)
            </tbody>
        </table>
    </div>
    <div class="middle_right_title" id="middle_right_bottom">
        <div class="middle_right_bottom_font">
            <label>
                <input type="checkbox" id="chk_checkall" />&nbsp;全选</label>
        </div>
        <div class="middle_right_bottom_font">
            结果 &nbsp;&nbsp;
            @(Model != null ? Model.CurrentCount : "0")/<label id="lblTotalCount">@(Model != null ? Model.TotalCount : 0)</label>
            &nbsp;
        </div>
        <div id="middle_right_goto" style="visibility: @(Model != null && !Model.DisplayAll ? "" : "hidden")">
            <a href="javascript:;">转到</a>
        </div>
        <div class="middle_right_font" style="visibility: @(Model != null && !Model.DisplayAll ? "" : "hidden")">
            第&nbsp;
            @Html.TextBoxFor(m => m.PageIndex, new { id = "txt_page" })
            &nbsp;页
        </div>
        <div id="middle_right_showall">
            <a href="javascript:;">
                @(Model != null && Model.DisplayAll ? "分页显示" : "显示全部")
            </a>
        </div>
        <div id="middle_right_prepage" style="visibility: @(Model != null && !Model.DisplayAll && Model.DataIMRecords.Any() && Model.PageIndex != 1 ? "" : "hidden")">
            <a href="javascript:;">上一页</a>
        </div>
        <div id="middle_right_nextpage" style="visibility: @(Model != null && !Model.DisplayAll && Model.DataIMRecords.Any() && !Model.IsLastPage ? "" : "hidden")">
            <a href="javascript:;">下一页</a>
        </div>
    </div>
    @Html.HiddenFor(m => m.IsNeedCalcPageIndex)
    @Html.HiddenFor(m => m.DisplayAll)
    @Html.HiddenFor(m => m.IsAutoSearch)
    @Html.HiddenFor(m => m.OrderField)
    @Html.HiddenFor(m => m.Order)
    @Html.HiddenFor(m => m.LocalNumber)
    @Html.HiddenFor(m => m.RemoteNumber)
    @Html.HiddenFor(m => m.GroupNumber)
    @Html.Hidden("hidTaskStatus", Model != null ? (int)Model.TaskStatus : -1)
    @Html.Hidden("hidPageIndex", Model == null ? 0 : Model.PageIndex)
    @Html.Hidden("hidMaxRecordId", Model == null || Model.DataIMRecords == null || !Model.DataIMRecords.Any() ? 0 : Model.DataIMRecords.Max(p => p.Id))
    @Html.Hidden("SearchId")
    
    <div id="exportConfirmContain" class="ui-helper-hidden">@Resources.MessageResource.ExportRecords_Confirm</div>
    <div id="imFilesContain" class="ui-helper-hidden"></div>
}